#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>

#include "cirbuf.h"

//#define DEBUG_CIRBUF

//----------------------------------------------------------------------------
// init buffer
//----------------------------------------------------------------------------
int init_cirbuf (cfg_t *cfg)
{
	if (cfg->buf_size <= 0) cfg->buf_size = 10;
	
	cfg->buf = malloc (sizeof (cirbuf_t));
	memset (cfg->buf, 0, sizeof (cirbuf_t));
	cfg->buf->pt = malloc (cfg->buf_size * sizeof (pt_t));
	memset (cfg->buf->pt, 0, cfg->buf_size * sizeof (pt_t));
	
	return 0;
}


//----------------------------------------------------------------------------
// add point to buffer
//----------------------------------------------------------------------------
int cirbuf_add_pt (cfg_t *cfg, pt_t *pt)
{
	if (cfg->buf->npt < cfg->buf_size) {
		cfg->buf->npt ++;
		cfg->buf->head = cfg->buf->npt - 1;
		memcpy (&cfg->buf->pt [cfg->buf->head], pt, sizeof (pt_t));		
	} 
	else {
		cfg->buf->head = (cfg->buf->head + 1) % cfg->buf->npt;
		cfg->buf->tail = (cfg->buf->head + 1) % cfg->buf->npt;
		memcpy (&cfg->buf->pt [cfg->buf->head], pt, sizeof (pt_t));	
	}
	
	return 0;	
}

//----------------------------------------------------------------------------
// copy data from cirbuf to plain buffer
//----------------------------------------------------------------------------
int cirbuf_to_buf (cirbuf_t *cirbuf, pt_t **pt)
{

	*pt = malloc (cirbuf->npt * sizeof (pt_t));
	if (*pt == NULL) return -1;
	
	if ((cirbuf->tail == 0)&& (cirbuf->head == (cirbuf->npt - 1))) {
		memcpy (*pt, cirbuf->pt, cirbuf->npt * sizeof (pt_t));
	}
	else {
		memcpy (*pt, &cirbuf->pt [cirbuf->tail], (cirbuf->npt - cirbuf->tail) * sizeof (pt_t));
		memcpy (&(*pt) [cirbuf->npt - cirbuf->tail], cirbuf->pt, (cirbuf->head + 1) * sizeof (pt_t)); 
	}
	
	return cirbuf->npt;
}
